import  React, {createContext, useState} from 'react';
import classNames from 'classnames';
import { MenuItemProps } from "./MenuItem"

// 字符串字面量
type MenuMode = "horizontal" | "vertical"
type SelectCallback = (selectedIndex: string) => void;


export interface MenuProps {
    defaultIndex ?: string;
    className ?: string;
    style ?: React.CSSProperties;
    mode ?: MenuMode;
    onSelect?: SelectCallback;
    defaultOpenSubMenus ?: string[];
}

interface IMenuContext {
    index: string;
    onSelect?: SelectCallback;
    mode ?: MenuMode;
    defaultOpenSubMenus?: string[];
}


export const MenuContext = createContext<IMenuContext>({index: "0"})

export const Menu: React.FC<MenuProps> = ({
    className,
    defaultIndex = "0",
    style,
    mode = "horizontal",
    onSelect,
    children,
    defaultOpenSubMenus = []
}) =>{

    const [ currentActive, setActive ] = useState(defaultIndex)

    const handleSelect = (index: string)=>{
        setActive(index)
        if (onSelect){
            onSelect(index)
        }
    }
    const passedContext : IMenuContext = {
        index: currentActive ? currentActive : "0",
        onSelect: handleSelect,
        mode,
        defaultOpenSubMenus
    }

    const classes = classNames("wave-menu", className, {
        "wave-menu-vertical": mode === "vertical",
        "wave-menu-horizontal": mode !== "vertical"
    })

    const renderChildren = () => {
        return React.Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<MenuItemProps>
            const { displayName} = childElement.type
            if (displayName === "MenuItem" || displayName === "SubMenu"){
                return React.cloneElement(childElement, {
                    index: index.toString()
                })
            } 
            console.error("error, child is not MenuItem")
            return 
        })
    }


    return (
        <ul style={style} className={classes} data-testid="test-menu">
            <MenuContext.Provider value={passedContext}>
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )
}

